package top.ooyyh.controller;

import top.ooyyh.model.User;
import top.ooyyh.service.UserService;
import top.ooyyh.util.TerminalUI;

import java.util.Scanner;

/**
 * 认证控制器（登录和注册）
 */
public class AuthController {
    private UserService userService = new UserService();
    private Scanner scanner = new Scanner(System.in);

    /**
     * 显示登录界面
     */
    public User showLogin() {
        TerminalUI.clearScreen();
        TerminalUI.printTitle("用户登录");
        
        System.out.print(TerminalUI.CYAN + "➜ " + TerminalUI.RESET + "请输入用户名: ");
        String username = scanner.nextLine().trim();
        
        System.out.print(TerminalUI.CYAN + "➜ " + TerminalUI.RESET + "请输入密码: ");
        String password = scanner.nextLine().trim();
        
        User user = userService.login(username, password);
        if (user != null) {
            TerminalUI.printSuccess("登录成功！欢迎，" + user.getUsername() + "！");
            TerminalUI.waitForEnter();
            return user;
        } else {
            TerminalUI.printError("用户名或密码错误！");
            TerminalUI.waitForEnter();
            return null;
        }
    }

    /**
     * 显示注册界面
     */
    public User showRegister() {
        TerminalUI.clearScreen();
        TerminalUI.printTitle("用户注册");
        
        System.out.print(TerminalUI.CYAN + "➜ " + TerminalUI.RESET + "请输入用户名: ");
        String username = scanner.nextLine().trim();
        
        if (username.isEmpty()) {
            TerminalUI.printError("用户名不能为空！");
            TerminalUI.waitForEnter();
            return null;
        }
        
        System.out.print(TerminalUI.CYAN + "➜ " + TerminalUI.RESET + "请输入密码（至少6位）: ");
        String password = scanner.nextLine().trim();
        
        if (password.length() < 6) {
            TerminalUI.printError("密码长度至少6位！");
            TerminalUI.waitForEnter();
            return null;
        }
        
        boolean success = userService.register(username, password);
        if (success) {
            TerminalUI.printSuccess("注册成功！");
            TerminalUI.waitForEnter();
            // 注册成功后自动登录
            return userService.login(username, password);
        } else {
            TerminalUI.printError("注册失败！用户名可能已存在。");
            TerminalUI.waitForEnter();
            return null;
        }
    }

    /**
     * 显示邮箱注册界面（预留，暂不实现）
     */
    public User showEmailRegister() {
        TerminalUI.clearScreen();
        TerminalUI.printTitle("邮箱注册");
        TerminalUI.printWarning("邮箱注册功能尚未实现，敬请期待！");
        TerminalUI.waitForEnter();
        return null;
    }
}

